const router = require("koa-router")();
var path = require("path");
var fs = require("fs");
var walk = require("walk");
var config = require("../config");

function readData(filePath) {
  console.log(" readData(filePath) filePath= ");
  console.log(filePath);
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) {
        console.log("读取文件发生错误");
        reject(err);
      }
      resolve(data);
    });
  });
}
function getObjType(obj) {
  // JavaScript 标准文档中定义: [[Class]] 的值只可能是下面字符串中的一个： Arguments, Array, Boolean, Date, Error, Function, JSON, Math, Number, Object, RegExp, String.
  var result = Object.prototype.toString.call(obj);
  result = result.match(/ \w+/)[0];
  result = result.replace(/ /g, "");
  return result;
}
function getDownloadUrls(fileList) {
  console.log(arguments.callee.name);
  console.log("fileList=" + fileList);
  console.log("fileList type =");
  console.log(getObjType(fileList));
  return new Promise((resolve, reject) => {
    try {
      var len = fileList.length;
      var urls = [];
      for (var i = 0; i < len; i++) {
        var filePath = fileList[i];
        console.log("filePath=" + filePath);
        var url = filePath.replace(config.dir, "127.0.0.1:3000/download?path=").replace("\\", "/");
        console.log(url);
        urls.push(url);
      }
      console.log("urls=");
      console.log(urls);
      resolve(urls);
    } catch (e) {
      console.log("文件路径转换为ulr发生错误");
      reject(e);
    }
  });
}
function getFileList() {
  return new Promise((resolve, reject) => {
    var dir = config.dir;
    var files = [];
    var dirs = [];
    var walker = walk.walk(dir, { followLinks: false });

    walker.on("file", function(roots, stat, next) {
      console.log("stat.name=" + stat.name);
      var extname = path.extname(stat.name);
      console.log("extname=" + extname);
      if (extname === config.extname) {
        files.push(roots + "/" + stat.name);
      }
      next();
    });

    walker.on("directory", function(roots, stat, next) {
      dirs.push(roots + "/" + stat.name);
      next();
    });
    walker.on("end", function() {
      console.log("files " + files);
      console.log("dirs " + dirs);
      resolve(files);
    });
    walker.on("error", function(er, entry, stat) {
      console.log("Got error " + er + " on entry " + entry);
      console.log("遍历文件发生错误");
      reject("遍历文件发生错误");
    });
  });
}

router.get("/", async (ctx, next) => {
  await ctx.render("index", {
    title: "Hello Koa 2!"
  });
});

router.get("/string", async (ctx, next) => {
  ctx.body = "koa2 string";
});

router.get("/json", async (ctx, next) => {
  ctx.body = {
    title: "koa2 json"
  };
});

router.get("/filelist", async (ctx, next) => {
  var fileList = await getFileList();
  var downloadUrls = await getDownloadUrls(fileList);
  ctx.body = downloadUrls;
});
router.get("/download", async (ctx, next) => {
  let url = ctx.url;
  let ctx_query = ctx.query;
  let ctx_querystring = ctx.querystring;
  // {
  //   "url": "/download?path=/stylesheets/style.css",
  //   "ctx_query": {
  //     "path": "/stylesheets/style.css"
  //   },
  //   "ctx_querystring": "path=/stylesheets/style.css"
  // }
  // ctx.body = ctx_query.path;
  // ctx.body = __dirname;
  let filename = path.basename(ctx_query.path);
  ctx.set("Content-disposition", "attachment; filename=" + filename);
  ctx.set("Content-type", "application/octet-stream");
  let gReadData = await readData(path.join(config.dir, ctx_query.path));
  ctx.body = gReadData;
});

module.exports = router;
